package org.example.service.Impl;

import cn.jiyun.enums.ResultCodeEnum;
import cn.jiyun.exception.exception.PasswordErrorException;
import cn.jiyun.exception.exception.UsernameNotExistException;
import cn.jiyun.result.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.config.R;
import org.example.config.SmsConfig;
import org.example.mapper.UserMapper;
import org.example.pojo.User;
import org.example.pojo.vo.LoginReqVo;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(User user) {
        return this.baseMapper.login(user);
    }

    @Override
    public void register(User user) {
        this.baseMapper.register(user);
    }

    @Override
    public List<User> findAllPhone() {
        return this.baseMapper.findAllPhone();
    }

    @Override
    public R sendCode(String phone, String code) throws Exception {
        //生成随机数
        // 创建一个Random对象
        Random random = new Random();
        // 生成一个1000到9999之间的随机数
        int smsCode = 1000 + random.nextInt(9000);

//        log.info("生成随机数:{}", code);
        //发送短信
        SmsConfig.sendSms(phone,smsCode + "");
        log.info("发送短信:{}", smsCode);
        log.info("发送成功");
        return R.ok().put("code", smsCode);
    }

    @Override
    public User checkPhone(User user) {
        return this.baseMapper.checkPhone(user);
    }

    @Override
    public void updatePassword(User user) {
        this.baseMapper.updatePassword(user);
    }


//    @Override
//    public User login(LoginReqVo loginReqVo) {
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(User::getUsername,loginReqVo.getUsername());
//        User user = userMapper.selectOne(queryWrapper);
//        //用户名不存在
//        if (user==null){
//            log.info("用户名不存在");
//            throw new UsernameNotExistException(ResultCodeEnum.USERNAME_NOT_EXIST);
//        }
//        String password = user.getPassword();
//        //密码不正确
//        if (!password.equals(loginReqVo.getPassword())){
//            log.info("密码不正确");
//            throw new PasswordErrorException(ResultCodeEnum.PASSWORD_ERROR);
//        }
//        log.info("登录成功");
//        return Result.ok(ResultCodeEnum.SUCCESS);
//    }
}
